package com.alvis.media.service;

import com.alvis.media.viewmodel.admin.analysis.AIAnalysisResultVM;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * Python AI分析服务
 */
@Service
public class PythonAIAnalysisService {

    /**
     * 执行AI数据分析
     */
    public AIAnalysisResultVM executeAIAnalysis() throws Exception {
        InputStream configStream = null;

        try {
            // 1. 加载配置文件
            Properties properties = new Properties();
            configStream = getClass().getClassLoader().getResourceAsStream("python-config.properties");
            if (configStream == null) {
                throw new FileNotFoundException("配置文件 python-config.properties 未找到");
            }
            properties.load(new InputStreamReader(configStream, StandardCharsets.UTF_8));

            // 2. 从配置文件获取路径
            String pythonInterpreter = properties.getProperty("python.ai.interpreter.path", "python");
            String pythonScript = properties.getProperty("python.ai.script.path");
            String outputDir = properties.getProperty("python.ai.output.dir");

            if (pythonScript == null || pythonScript.isEmpty()) {
                throw new IllegalArgumentException("Python脚本路径未配置");
            }

            // 3. 确保输出目录存在
            File outputDirFile = new File(outputDir);
            if (!outputDirFile.exists()) {
                outputDirFile.mkdirs();
            }

            // 4. 定义命令数组
            String[] cmd = {pythonInterpreter, pythonScript};

            // 5. 启动进程执行命令
            System.out.println("执行Python命令: " + String.join(" ", cmd));
            System.out.println("Python脚本路径: " + pythonScript);

            // 检查Python脚本文件是否存在
            File scriptFile = new File(pythonScript);
            if (!scriptFile.exists()) {
                throw new FileNotFoundException("Python脚本文件不存在: " + pythonScript);
            }

            ProcessBuilder processBuilder = new ProcessBuilder(cmd);
            // 不合并stderr到stdout,保持分离
            // processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();

            // 6. 读取Python的标准输出(JSON结果)和错误输出
            BufferedReader stdoutReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)
            );
            BufferedReader stderrReader = new BufferedReader(
                    new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8)
            );

            String line;
            StringBuilder jsonOutput = new StringBuilder();
            StringBuilder errorOutput = new StringBuilder();

            // 读取标准输出(JSON结果)
            while ((line = stdoutReader.readLine()) != null) {
                // 标准输出应该是纯JSON,不打印到控制台
                jsonOutput.append(line).append("\n");
            }

            // 读取错误输出(诊断信息)
            while ((line = stderrReader.readLine()) != null) {
                System.out.println("Python AI分析日志：" + line);
                if (line.contains("Error") || line.contains("Exception") || line.contains("Traceback")) {
                    errorOutput.append(line).append("\n");
                }
            }

            // 7. 等待脚本执行完成
            int exitCode = process.waitFor();
            System.out.println("AI分析脚本执行结束,退出码:" + exitCode);

            if (exitCode != 0) {
                String errorMsg = errorOutput.length() > 0 ? errorOutput.toString() : "执行失败,无详细错误信息";
                System.err.println("Python脚本执行失败,详细错误:\n" + errorMsg);
                throw new RuntimeException("Python脚本执行失败,退出码: " + exitCode + "\n错误详情: " + errorMsg);
            }

            // 8. 解析JSON结果(直接从stdout)
            String jsonResult = jsonOutput.toString().trim();
            if (jsonResult.isEmpty()) {
                throw new RuntimeException("Python脚本未返回任何结果");
            }

            System.out.println("收到AI分析JSON结果,长度: " + jsonResult.length() + " 字符");

            ObjectMapper objectMapper = new ObjectMapper();
            AIAnalysisResultVM result = objectMapper.readValue(
                jsonResult,
                AIAnalysisResultVM.class
            );

            System.out.println("成功解析AI分析结果");
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("执行AI分析时发生错误: " + e.getMessage(), e);
        } finally {
            // 关闭配置文件流
            if (configStream != null) {
                try {
                    configStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
